package com.itchen.school.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.CopyOption;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileExistsException;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SysFileUtils extends FileUtils {

    private static final Logger log = LoggerFactory.getLogger(SysFileUtils.class);

    public SysFileUtils() {}

    public static String getTimedFileName() {
        long var10000 = System.currentTimeMillis();
        return var10000 + (int)(Math.random() * 100000.0D)+"";
    }

    public static String getExtensionName(String fileName) {
        int slashPos = fileName.lastIndexOf(47);
        if (slashPos < 0) {
            slashPos = fileName.lastIndexOf(92);
        }

        if (slashPos >= 0) {
            fileName = fileName.substring(slashPos + 1);
        }

        if (fileName.length() == 0) {
            return null;
        } else {
            slashPos = fileName.lastIndexOf(46);
            if (slashPos >= 0) {
                fileName = fileName.substring(slashPos + 1);
            }

            return fileName;
        }
    }

    public static String getExtensionName(File file) {
        String name = file.getName();
        if (name.endsWith(".")) {
            return "";
        } else {
            int dotPos = name.lastIndexOf(46);
            return dotPos >= 0 ? name.substring(dotPos + 1) : "";
        }
    }

    public static String getBaseName(String fileName) {
        int slashPos = fileName.lastIndexOf(47);
        if (slashPos < 0) {
            slashPos = fileName.lastIndexOf(92);
        }

        if (slashPos >= 0) {
            fileName = fileName.substring(slashPos + 1);
        }

        if (fileName.length() == 0) {
            return null;
        } else {
            slashPos = fileName.lastIndexOf(46);
            if (slashPos >= 0) {
                fileName = fileName.substring(0, slashPos);
            }

            return fileName;
        }
    }

    public static String getBaseName(File file) {
        String name = file.getName();
        int dotPos = name.lastIndexOf(46);
        return dotPos >= 0 ? name.substring(0, dotPos) : name;
    }

    public static boolean getImageFormat(String suffix) {
        return "TFF".equalsIgnoreCase(suffix) || "TIFF".equalsIgnoreCase(suffix) || "PNG".equalsIgnoreCase(suffix) || "GIF".equalsIgnoreCase(suffix) || "JPG".equalsIgnoreCase(suffix) || "JPEG".equalsIgnoreCase(suffix);
    }

    public static File saveFileToDisk(InputStream stream, String savePath) {
        File localFile = new File(savePath);
        if (!localFile.getParentFile().exists()) {
            localFile.getParentFile().mkdirs();
        }

        try {
            Files.copy(stream, Paths.get(savePath), new CopyOption[]{StandardCopyOption.REPLACE_EXISTING});
            return localFile;
        } catch (IOException var4) {
            log.error("保存文件失败");
            return null;
        }
    }

    public static void saveFile(byte[] content, String filePath, String fileName) throws Exception {
        File targetFile = new File(filePath);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        if (!filePath.endsWith(File.separator)) {
            filePath = filePath + File.separator;
        }

        Files.write(Paths.get(filePath + fileName), content, new OpenOption[]{StandardOpenOption.CREATE});
    }

    public static void saveFile(byte[] content, String filePath, String fileName, boolean overwrite) throws Exception {
        if (overwrite) {
            saveFile(content, filePath, fileName);
        } else {
            if (!filePath.endsWith(File.separator)) {
                filePath = filePath + File.separator;
            }

            File nf = new File(filePath + fileName);
            if (nf.exists()) {
                throw new FileExistsException();
            } else {
                saveFile(content, filePath, fileName);
            }
        }
    }

    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                log.error("删除单个文件-> {}成功！", fileName);
                return true;
            } else {
                log.error("删除单个文件-> {}失败！", fileName);
                return false;
            }
        } else {
            log.info("删除单个文件失败-> {}不存在！", fileName);
            return false;
        }
    }

    public static void downLoadFile(HttpServletResponse response, String fileLocal, String downloadName, boolean deleteFile) {
        if (!"".equals(downloadName)) {
            downloadName = downloadName + fileLocal.substring(fileLocal.lastIndexOf("."));
        } else {
            downloadName = fileLocal.substring(fileLocal.lastIndexOf("/") + 1);
        }

        boolean var17 = false;

        File file;
        label143: {
            try {
                var17 = true;
                FileInputStream in = new FileInputStream(fileLocal);

                try {
                    response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(downloadName, "UTF-8"));
                    byte[] buffer = new byte[1024];
                    ServletOutputStream out = response.getOutputStream();

                    int len;
                    while((len = in.read(buffer)) > 0) {
                        out.write(buffer, 0, len);
                    }
                } catch (Throwable var22) {
                    try {
                        in.close();
                    } catch (Throwable var20) {
                        var22.addSuppressed(var20);
                    }

                    throw var22;
                }

                in.close();
                var17 = false;
                break label143;
            } catch (Exception var23) {
                var17 = false;
            } finally {
                if (var17) {
                    try {
                        if (deleteFile) {
                            Thread.sleep(1000L);
                            file = new File(fileLocal);
                            file.delete();
                        }
                    } catch (Exception var18) {
                    }

                }
            }

            try {
                if (deleteFile) {
                    Thread.sleep(1000L);
                    file = new File(fileLocal);
                    file.delete();
                    return;
                }
            } catch (Exception var19) {
            }

            return;
        }

        try {
            if (deleteFile) {
                Thread.sleep(1000L);
                file = new File(fileLocal);
                file.delete();
            }
        } catch (Exception var21) {
        }

    }

    public static boolean createFile(String descFileName) {
        File file = new File(descFileName);
        if (file.exists()) {
            log.debug("文件 " + descFileName + " 已存在!");
            return false;
        } else if (descFileName.endsWith(File.separator)) {
            log.debug(descFileName + " 为目录，不能创建目录!");
            return false;
        } else if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) {
            log.debug("创建文件所在的目录失败!");
            return false;
        } else {
            try {
                if (file.createNewFile()) {
                    log.debug(descFileName + " 文件创建成功!");
                    return true;
                } else {
                    log.debug(descFileName + " 文件创建失败!");
                    return false;
                }
            } catch (Exception var3) {
                log.debug(descFileName + " 文件创建失败!");
                return false;
            }
        }
    }

    public static boolean createDirectory(String descDirName) {
        String descDirNames = descDirName;
        if (!descDirName.endsWith(File.separator)) {
            descDirNames = descDirName + File.separator;
        }

        File descDir = new File(descDirNames);
        if (descDir.exists()) {
            log.debug("目录 " + descDirNames + " 已存在!");
            return true;
        } else if (descDir.mkdirs()) {
            log.debug("目录 " + descDirNames + " 创建成功!");
            return true;
        } else {
            log.debug("目录 " + descDirNames + " 创建失败!");
            return false;
        }
    }

    public static void writeToFile(String fileName, String content, boolean append) {
        try {
            FileUtils.write(new File(fileName), content, "utf-8", append);
            log.debug("文件 " + fileName + " 写入成功!");
        } catch (IOException var4) {
            log.debug("文件 " + fileName + " 写入失败! " + var4.getMessage());
        }

    }

    public static void writeToFile(String fileName, String content, String encoding, boolean append) {
        try {
            FileUtils.write(new File(fileName), content, encoding, append);
            log.debug("文件 " + fileName + " 写入成功!");
        } catch (IOException var5) {
            log.debug("文件 " + fileName + " 写入失败! " + var5.getMessage());
        }

    }

    public static String concatPaths(boolean needEndSlash, String... paths) {
        if (SysCollectionUtils.isEmpty(paths)) {
            return "";
        } else {
            String path = paths[0];
            if (path != null) {
                path = path.replace("\\", "/");
            }

            if (path == null) {
                path = "";
            }

            if (!path.endsWith("/")) {
                path = path + "/";
            }

            for(int i = 1; i < paths.length; ++i) {
                String tPath = paths[i];
                if (!StringUtils.isEmpty(tPath)) {
                    tPath = tPath.replace("\\", "/");
                    if (tPath.startsWith("/")) {
                        tPath = tPath.substring(1);
                    }

                    if (!tPath.endsWith("/")) {
                        tPath = tPath + "/";
                    }

                    if (!tPath.equals("/")) {
                        path = path + tPath;
                    }
                }
            }

            if (needEndSlash) {
                if (!path.endsWith("/")) {
                    path = path + "/";
                }
            } else if (path.endsWith("/")) {
                path = path.substring(0, path.length() - 1);
            }

            return path;
        }
    }

    public static String getPathLastPart(String path, String delmi, boolean emptyIfNoDelmi) {
        int slashIndex = path.lastIndexOf(delmi);
        if (slashIndex > 0) {
            return path.substring(slashIndex + delmi.length() + 1);
        } else {
            return emptyIfNoDelmi ? "" : path;
        }
    }

}

